package com.example.xss.client;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * notin api
 */
@Slf4j
public class NotionClient {
    /**
     * 父页面id
     */
    private final static String PARENT_PAGE_ID = "ed078c45e17c4c57a26de17b1c75dea5";
    /**
     * 父数据表id
     */
    private final static String PARENT_DATABASE_ID = "c0190a324dc54dfea6c2afd465ae48eb";

    /**
     * host
     */
    private final static String HOST = "https://api.notion.com/";
    /**
     * token
     */
    private final static String AUTHORIZATION = "Bearer secret_gPt0zluHAE4giRcE2MZVghLms9CmkT3566QDndftGog";

    /**
     * api版本
     */
    private final static String NOTION_VERSION = "2021-08-16";


    /**
     * notion api的标准请求
     *
     * @param url  对象不含host
     * @param json 参数值
     * @return 返回结果
     */
    public static JSONObject post(String url, String json) {
        log.info("请求参数：url{},json:{}", url, json);
        String body = HttpRequest.post(HOST + url)
                .contentType("application/json;charset=UTF-8")
                .header("Authorization", AUTHORIZATION)
                .header("Notion-Version", NOTION_VERSION)
                .body(json)
                .execute().body();
        log.info("请求返回结果：{}", body);
        return JSONUtil.parseObj(body);
    }

    /**
     * 在分类数据库中创建新页面
     *
     * @return 创建结果
     */
    public static String createPageOfDb(String name, String code, String statistical) {
        String json = "{\"icon\": {\"emoji\": \"\uD83D\uDC36\", \"type\": \"emoji\"}, \"parent\": {\"database_id\": \"{}\"}, \"properties\": {\"公司名称\": {\"title\": [{\"text\": {\"content\": \"{}\"}}]}, \"股票代码\": {\"rich_text\": [{\"text\": {\"content\": \"{}\"}}]}, \"周期\": {\"rich_text\": [{\"text\": {\"content\": \"{}\"}}]}, \"统计时间\": {\"date\": {\"start\": \"{}\"}}}}";
        json= String.format(json, name, code, statistical, DateUtil.date());
        JSONObject res = post("v1/pages", json);
        if (ObjectUtil.isNull(res)) {
            log.error("createPageOfDb 请求失败");
            return null;
        }
        // 得到页面id
        return res.getStr("id");
    }


}
